<template>
	<div class="zhiShiFenLei">
		<!-- 主体表格 -->
		<div class="left" v-if="!visible">
			<div class="bfff left-bottom">
				<div class="center flex-start fWrap table-head">
					<el-button
						type="primary"
						:size="large"
						@click="addList"
						v-auth="['knowledge:kbSubjectWarehouse:add']"
						>+新增</el-button
					>
					<!-- <el-button
						class="danger"
						type="danger"
						@click="delDirectory"
						plain
						v-auth="['knowledge:kbSubjectWarehouse:delete']"
						>删除
					</el-button> -->
				</div>
				<div class="table-scrol">
					<div class="table">
						<el-table @cell-click="cellClick" :data="tableData" highlight-current-row style="width: 100%">
							<el-table-column
								align="center"
								prop="name"
								label="知识库名称"
								show-overflow-tooltip
								min-width="200"
							/>
							<el-table-column
								align="center"
								prop="sort"
								label="权重"
								show-overflow-tooltip
								min-width="50"
							/>
							<el-table-column align="center" label="操作" min-width="200">
								<template #default="{ row }">
									<el-button
										plain
										icon="EditPen"
										@click="edit(row)"
										v-auth="[
											'knowledge:kbSubjectWarehouse:edit',
											'knowledge:kbSubjectWarehouse:findById',
										]"
										title="编辑"
									></el-button>
									<el-button
										plain
										icon="Remove"
										@click="limits(row)"
										v-auth="[
											'knowledge:kbWarehouseAuth:edit',
											'knowledge:kbWarehouseAuth:findBySwId',
										]"
										title="权限调整"
									></el-button>
									<el-button
										plain
										icon="Delete"
										@click="delDirectory(row)"
										v-auth="['knowledge:kbSubjectWarehouse:delete']"
										title="删除"
									></el-button>
								</template>
							</el-table-column>
							<template #empty>
								<el-empty description="暂无数据" />
							</template>
						</el-table>
					</div>
				</div>
			</div>
		</div>
		<!-- 新增主题知识库目录设置 -->
		<div class="left bfff cheng-dialog" v-else>
			<div class="center title">
				<i class="iconfont f26 mr15">&#xe811;</i>
				<div class="f16 c333 flex">{{ title }}</div>
			</div>
			<el-form
				:label-position="labelPosition"
				ref="ruleFormRef"
				:model="ruleForm"
				:rules="rules"
				class="demo-ruleForm"
				status-icon
			>
				<el-form-item label="主题知识库名称" prop="name">
					<el-input
						class="name"
						v-model="ruleForm.name"
						placeholder="请输入主题知识库名称"
						maxlength="20"
						show-word-limit
					/>
				</el-form-item>
				<el-form-item label="是否在首页展示" prop="isShow" v-if="status != 2">
					<el-switch v-model="ruleForm.isShow" active-text="是" active-value="1" inactive-value="2" />
				</el-form-item>
				<el-form-item label="权重" prop="sort" v-if="status != 2">
					<template #label>
						<span>权重</span>
						<el-tooltip class="box-item" effect="dark" content="数字越大越靠前" placement="top" :offset="0">
							<el-icon class="label-icon"><InfoFilled /></el-icon>
						</el-tooltip>
					</template>
					<template #default>
						<el-input-number v-model="ruleForm.sort" :min="1" />
					</template>
				</el-form-item>
				<el-form-item label="主题知识库描述" prop="remark">
					<el-input
						type="textarea"
						class="name"
						v-model="ruleForm.remark"
						placeholder="请输入主题知识库描述"
						maxlength="200"
						show-word-limit
					/>
				</el-form-item>
				<el-form-item label="属性模板" prop="attribute" v-if="status != 2 && editIf">
					<div class="center w100">
						<div class="flex">
							<el-select collapse-tags class="bu-select" v-model="ruleForm.attribute">
								<el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
							<div class="refresh" @click="refresh">
								<!-- <div>点击刷新</div>
								<div class="refresh-icon">
									<el-icon><RefreshLeft /></el-icon>
								</div> -->
								<el-button :icon="RefreshLeft" circle />
							</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="上传封面" prop="cover" ref="imgRef">
					<div>
						<el-upload
							class="avatar-uploader"
							action=""
							:show-file-list="false"
							:before-upload="beforeAvatarUpload"
							:auto-upload="false"
							:on-change="onChangeUpload"
							ref="upload"
							:limit="1"
						>
							<!-- @on-success="onSuccess" -->
							<img v-if="ruleForm.cover" :src="ruleForm.cover" class="avatar" />
							<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
						</el-upload>
						<div class="f14 c90 mt30">
							注：只能上传jpg/png文件，推荐上传尺寸比例为 16:9 的封面图，且图片大小不超过2M
						</div>
						<VCropper ref="cropper" @success="handleAvatarSuccess" :title="'封面'"> </VCropper>
					</div>
				</el-form-item>
				<el-divider border-style="dashed" />
				<div>
					<div class="center title">
						<img src="@/assets/image/houTai/quanXian.png" class="quanXian-icon" alt="" />
						<div class="f16 c333 flex">知识库权限</div>
						<el-button type="primary" link :icon="CirclePlusFilled" @click="onDialog('1')"
							>添加成员</el-button
						>
					</div>
					<div
						class="center quanXian-content"
						v-for="(item, index) in stagingA[currentNameA - 1]"
						:key="index"
					>
						<img src="@/assets/image/houTai/tou.png" class="tou-icon" alt="" />
						<div class="f16 c60">{{ item.userName }}</div>
						<div class="flex f14 quanXian-right">
							<div v-if="!index == 0 || currentNameA != '1'" class="flex f20 center">
								<div class="flex"></div>
								<el-select
									v-model="authsList[index + (currentNameA - 1) * 5].whAuth"
									placeholder="请选择"
								>
									<el-option
										v-for="item in cata"
										:key="item.code"
										:label="item.name"
										:value="+item.code"
									>
										<div class="option-content">
											<div class="f14 c60">{{ item.name }}</div>
											<div class="f12 c1c">{{ item.desc }}</div>
										</div>
									</el-option>
								</el-select>
								<el-button class="selectDel" @click="delAuth(index + (currentNameA - 1) * 5, '1')">
									删除
								</el-button>
							</div>
							<div v-else class="suoyou f16"><span>所有者</span></div>
						</div>
					</div>
					<div class="pag-centent">
						<el-pagination
							layout="prev, pager, next"
							hide-on-single-pag
							v-model:current-page="currentNameA"
							v-model:page-size="pagesize"
							:total="authsList.length"
						/>
					</div>
				</div>
				<el-divider border-style="dashed" />
				<div>
					<div class="center title">
						<img src="@/assets/image/houTai/quanXian.png" class="quanXian-icon" alt="" />
						<div class="f16 c333 flex">知识分类权限</div>
						<el-button type="primary" link :icon="CirclePlusFilled" @click="onDialog('2')"
							>添加成员</el-button
						>
					</div>
					<div
						class="center quanXian-content"
						v-for="(item, index) in stagingB[currentNameB - 1]"
						:key="index"
					>
						<img src="@/assets/image/houTai/tou.png" class="tou-icon" alt="" />
						<div class="f16 c60">{{ item.userName }}</div>
						<div class="flex f20 quanXian-right">
							<div v-if="!index == 0 || currentNameB != '1'" class="flex f20 center">
								<div class="flex"></div>
								<el-select
									v-model="authsListItem[index + (currentNameB - 1) * 5].kbAuth"
									placeholder="请选择"
								>
									<el-option
										v-for="item in qoptions"
										:key="item.code"
										:label="item.name"
										:value="+item.code"
									>
										<div class="option-content">
											<div class="f14 c60">{{ item.name }}</div>
											<div class="f12 c1c">{{ item.desc }}</div>
										</div>
									</el-option>
								</el-select>
								<el-button class="selectDel" @click="delAuth(index + (currentNameB - 1) * 5, '2')"
									>删除</el-button
								>
							</div>
							<div v-else class="suoyou f16"><span>所有者</span></div>
						</div>
					</div>
					<div class="pag-centent">
						<el-pagination
							layout="prev, pager, next"
							hide-on-single-pag
							v-model:current-page="currentNameB"
							v-model:page-size="pagesize"
							:total="authsListItem.length"
						/>
					</div>
				</div>
				<el-form-item label="" class="form-footer">
					<div class="el-form-item__label"></div>
					<el-button @click="quxiao1">取消</el-button>
					<el-button type="primary" @click="submitForm(ruleFormRef)"> 提交 </el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 权限调整弹窗 -->
		<el-dialog
			top="5vh"
			class="quan-dialog"
			v-model="quanVisible"
			:show-close="false"
			:close-on-click-modal="false"
			destroy-on-close
		>
			<template #header="{ close, titleId, titleClass }">
				<div class="dialog-header center btheme cfff">
					<img src="@/assets/image/houTai/quan.png" alt="" />
					<div class="flex f16 fbold">权限调整</div>
					<el-icon class="pointer" size="20" color="#fff" @click="quanVisible = false">
						<Close />
					</el-icon>
				</div>
			</template>
			<div class="dialog-content">
				<div>
					<div class="center title">
						<img src="@/assets/image/houTai/quanXian.png" class="quanXian-icon" alt="" />
						<div class="f16 fbold c333">知识库权限</div>
						<el-button type="primary" link :icon="CirclePlusFilled" @click="onDialog('3')"
							>添加成员</el-button
						>
						<div class="flex"></div>
						<el-button type="primary" link @click="setQuanMore">{{ quanMore ? "收起" : "展开" }}</el-button>
					</div>
					<template v-if="quanMore">
						<div v-for="(item, index) in stagingC[currentNameC - 1]" :key="item.id">
							<div class="center quanXian-content">
								<img src="@/assets/image/houTai/tou.png" class="tou-icon" alt="" />
								<div class="f14 c60">{{ item.userName }}</div>
								<div class="flex f20 quanXian-right">
									<div v-if="!index == 0 || currentNameC != '1'" class="flex f20 center">
										<div class="flex"></div>
										<el-select
											v-model="authorityA[index + (currentNameC - 1) * 5].whAuth"
											placeholder="请选择"
										>
											<el-option
												v-for="item in cata"
												:key="item.code"
												:label="item.name"
												:value="+item.code"
											>
												<div class="option-content">
													<div class="f14 c60">{{ item.name }}</div>
													<div class="f12 c1c">{{ item.desc }}</div>
												</div>
											</el-option>
										</el-select>
										<el-button
											class="selectDel"
											@click="delAuth(index + (currentNameC - 1) * 5, '3')"
											>删除</el-button
										>
									</div>
									<div v-else class="suoyou f16"><span>所有者</span></div>
								</div>
							</div>
						</div>
						<div class="pag-centent">
							<el-pagination
								layout="prev, pager, next"
								hide-on-single-pag
								v-model:current-page="currentNameC"
								v-model:page-size="pagesize"
								:total="authorityA.length"
							/>
						</div>
					</template>
				</div>
				<div class="mt50">
					<div class="center title">
						<img src="@/assets/image/houTai/quanXian.png" class="quanXian-icon" alt="" />
						<div class="f16 fbold c333">知识分类权限</div>
						<el-button type="primary" link :icon="CirclePlusFilled" @click="onDialog('4')"
							>添加成员</el-button
						>
						<div class="flex"></div>
						<el-button type="primary" link @click="setQuanMore2">{{
							quanMore2 ? "收起" : "展开"
						}}</el-button>
					</div>
					<template v-if="quanMore2">
						<div
							class="center quanXian-content"
							v-for="(item, index) in stagingD[currentNameD - 1]"
							:key="item.id"
						>
							<img src="@/assets/image/houTai/tou.png" class="tou-icon" alt="" />
							<div class="f14 c60">{{ item.userName }}</div>
							<div class="flex f20 quanXian-right">
								<div v-if="!index == 0 || currentNameD != '1'" class="flex f16 center">
									<div class="flex"></div>
									<el-select
										v-model="authorityB[index + (currentNameD - 1) * 5].kbAuth"
										placeholder="请选择"
									>
										<el-option
											v-for="item in qoptions"
											:key="item.code"
											:label="item.name"
											:value="+item.code"
										>
											<div class="option-content">
												<div class="f14 c60">{{ item.name }}</div>
												<div class="f12 c1c">{{ item.desc }}</div>
											</div>
										</el-option>
									</el-select>
									<el-button class="selectDel" @click="delAuth(index + (currentNameD - 1) * 5, '4')"
										>删除</el-button
									>
								</div>
								<div v-else class="suoyou f16"><span>所有者</span></div>
							</div>
						</div>
						<div class="pag-centent">
							<el-pagination
								layout="prev, pager, next"
								v-model:current-page="currentNameD"
								v-model:page-size="pagesize"
								:total="authorityB.length"
							/>
						</div>
					</template>
				</div>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="quxiao2">取消</el-button>
					<el-button type="primary" @click="isLimits"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 新增用户 -->
		<el-dialog
			top="5vh"
			class="quan-dialog"
			v-model="dialogVisible"
			:show-close="false"
			:close-on-click-modal="false"
			destroy-on-close
		>
			<template #header="{ close, titleId, titleClass }">
				<div class="dialog-header center btheme cfff">
					<img src="@/assets/image/zhuTi/x6.png" alt="" />
					<div class="flex f18 fbold">新增成员</div>
					<el-icon class="pointer" size="20" color="#fff" @click="cancellationB">
						<Close />
					</el-icon>
				</div>
			</template>
			<div class="dialog-content-cheng">
				<div class="fWrap center align-start">
					<div class="dleft">
						<el-tabs type="border-card" v-model="activeName" @tab-click="tabclick">
							<el-tab-pane label="按部门分类" name="department">
								<div class="tab-content">
									<div class="f18 c333 tCenter">部门列表</div>
									<div class="bfff tree-box">
										<el-tree
											@node-click="tabListStr"
											:data="dataSourceList"
											:props="defaultProps"
										></el-tree>
									</div>
								</div>
							</el-tab-pane>
							<el-tab-pane label="按群组分类" name="group">
								<div class="tab-content">
									<div class="f18 c333 tCenter">群组列表</div>
									<div class="bfff tree-box">
										<el-tree
											@node-click="tabListStr"
											:data="dataSourceList"
											:props="defaultProps"
										></el-tree>
									</div>
								</div>
							</el-tab-pane>
						</el-tabs>
					</div>
					<div class="flex dright">
						<el-input v-model="searchText" class="search-input" placeholder="请输入用户名搜索">
							<template #append>
								<el-button class="search-btn" type="primary" :icon="Search" @click="onSearch"
									>搜索</el-button
								>
							</template>
						</el-input>
						<el-table
							ref="multipleTableRef"
							:data="tableDataCheng[currentTable - 1]"
							style="width: 100%"
							@select="onSelect"
							@select-all="selectAllTable"
							@cell-click="onSelects"
						>
							<el-table-column type="selection" min-width="15%" />
							<el-table-column prop="realName" min-width="75%">
								<template #default="{ row }">
									<div v-if="row.realName">{{ row.realName }}</div>
									<div v-if="row.name">{{ row.name }}</div>
								</template>
							</el-table-column>
						</el-table>
						<div style="display: flex; justify-content: center">
							<el-pagination
								layout="prev, pager, next"
								v-model:current-page="currentTable"
								v-model:page-size="pageSizeTable"
								:total="totalList"
							></el-pagination>
						</div>
					</div>
				</div>
				<div class="center choice">
					<div class="f16 c333">用户选择：</div>
					<div class="flex">
						<el-tag
							closable
							type="primary"
							effect="plain"
							round
							@close="clickDelTag(index)"
							v-for="(item, index) in tableUser"
							:key="item.userId"
							>{{ item.userName }}</el-tag
						>
					</div>
					<el-button class="clear-btn" type="warning" @click="delTableList">清空选择</el-button>
				</div>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="cancellationB">取消</el-button>
					<el-button type="primary" @click="onAddList"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import {
	Search,
	RefreshRight,
	EditPen,
	Delete,
	CirclePlusFilled,
	InfoFilled,
	Remove,
	RefreshLeft,
} from "@element-plus/icons-vue"
import { useSettingStores } from "@/store/settings"
import { ElMessage, ElMessageBox } from "element-plus"
import VCropper from "../../../components/cropper/index.vue"
const settingStore = useSettingStores()
const labelPosition = computed(() => (settingStore.isMobile ? "top" : "right"))
const { proxy } = getCurrentInstance()
const multipleTableRef = ref()
const route = useRoute()
const router = useRouter()
const currentTable = ref(1)
const pageSizeTable = ref(8)
const totalList = ref(null)
const stagingA = ref([])
const stagingB = ref([])
const stagingC = ref([])
const stagingD = ref([])
const currentNameA = ref(1)
const currentNameB = ref(1)
const currentNameC = ref(1)
const currentNameD = ref(1)
const pagesize = ref(5)
// 新增主题知识库目录设置
const visible = ref(false)
const setShowMore = () => {
	visible.value = !visible.value
}
const typeStr = ref(null)
const defaultProps = reactive({
	children: "children",
	label: "name",
})
const currentType = ref(null)
// const staging = ref([])
const key = ref(null)
//已选择权限
const authsList = ref([])
const authsListItem = ref([])
const classificationStr = ref({})
//title设置
const title = ref("")
// 权限调整弹窗
const quanVisible = ref(false)

const quanMore = ref(true)

const quanMore2 = ref(true)
const total = ref(0)
const current = ref(1)

//目录权限已选择
const subscriber = ref([])
const tableDataCheng = ref([])
const findSize = ref(1)
const findTotal = ref(null)
const findpage = ref(10)
//目录下的权限已选择
const subscriberItem = ref([])
//权限调整
const authorityA = ref([])
//添加成员
const dataSourceList = ref([])
const rowId = ref("")
const tableUser = ref([])
const authorityB = ref([])
const limitsListA = ref([])
const limitsListB = ref([])
const ruleForm = reactive({
	name: "",
	sort: 1,
	isShow: "2",
	remark: "",
	attribute: "",
	cover: "",
})
const searchText = ref("")
const dialogVisible = ref(false)
const setQuanMore = () => {
	quanMore.value = !quanMore.value
}
const setQuanMore2 = () => {
	quanMore2.value = !quanMore2.value
}

//图片
const qoptions = ref([])
const activeName = ref("department")
const listA = ref([])
const listB = ref([])
const editIf = ref(true)
const listC = ref([])
const listD = ref([])
const options = ref([])
const imgRef = ref("")
const rules = reactive({
	name: [{ required: true, message: "请输入知识库名称", trigger: "blur" }],
	remark: [{ required: true, message: "请输入知识库描述", trigger: "blur" }],
	attribute: [{ required: true, message: "请选择属性模板", trigger: "change" }],
	cover: [{ required: true, message: "请上传封面", trigger: "change" }],
})
const checked1 = ref(true)
const checked2 = ref(false)
const ids = ref("")

const cata = ref([])

async function getCata() {
	const res = await getAxios("/system/enums/list?enumName=WhAuth&moduleName=knowledge")
	cata.value = res
}
getCata()

const submitForm = async formEl => {
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		if (!formEl) return
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				const obj = {}
				if (ids.value != "") {
					obj.id = ids.value
				}
				obj.name = ruleForm.name
				obj.modelId = ruleForm.attribute
				obj.remark = ruleForm.remark
				obj.cover = ruleForm.cover
				obj.sort = ruleForm.sort
				obj.isShow = ruleForm.isShow
				obj.status = "1"
				obj.knowledgeAuthList = authsList.value
				obj.classAuthsList = authsListItem.value
				let quanxian = false
				authsListItem.value.forEach(item => {
					if (item.kbAuth == null) {
						quanxian = true
					}
				})
				if (quanxian) {
					ElMessage.error("权限不能为空")
					fabu.value = false
				} else {
					if (ids.value == "") {
						try {
							await postAxios("/knowledge/kbSubjectWarehouse/add", obj)
							ElMessage.success("新建成功")
							visible.value = false
							created()
							del()
						} catch (error) {
							ElMessage.error(error)
							fabu.value = false
						}
					} else {
						try {
							await postAxios("/knowledge/kbSubjectWarehouse/edit", obj)
							ElMessage.success("修改成功")
							visible.value = false
							created()
							del()
						} catch (error) {
							ElMessage.error(error)
							fabu.value = false
						}
					}
				}
			} else {
				fabu.value = false
			}
		})
	}
}
//上传限制
const beforeAvatarUpload = rawFile => {
	if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
		ElMessage.error("请上传png/jpeg格式文件")
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error("图片大小不能超过2MB!")
		return false
	}
	return true
}
const ruleFormRef = ref()
const status = ref(1)
const tableData = ref([])
async function created() {
	const res = await getAxios("/knowledge/kbSubjectWarehouse/page")
	if (res) {
		// total.value = +res.total
		tableData.value = res
	}
}
created()
//新增
const addList = async () => {
	editIf.value = true
	ids.value = ""
	title.value = "新增主题知识库"
	fabu.value = false
	status.value = 1
	visible.value = true
	stagingA.value = []
	stagingB.value = []
	const user = await getAxios("/system/sysUser/personInfo")
	authsList.value = [
		{
			userName: user.realName,
			userId: user.id,
			whAuth: 1, //状态
			status: 1,
		},
	]
	authsListItem.value = [
		{
			userName: user.realName,
			userId: user.id,
			kbAuth: 5, //状态
			status: 1,
		},
	]
	stagingA.value = sliceArr(authsList.value, pagesize.value)
	stagingB.value = sliceArr(authsListItem.value, pagesize.value)
	const res = await getAxios("/kb/kbModel/list?is_deleted=2")
	options.value = res
	qoptions.value = await getAxios("/system/enums/list?enumName=KbAuth&moduleName=knowledge")
	listA.value = authsList.value
	listB.value = authsListItem.value
	currentNameA.value = 1
	currentNameB.value = 1
}

const upfile = async params => {
	const file = params.file
	const formData = new FormData()
	formData.append("upfile", file)
	const { url } = await postAxios("/system/oss/upload", formData)
	ruleForm.cover = url
}
//删除
const delAuth = (index, item) => {
	fabu.value = false
	switch (item) {
		case "1":
			if (authsList.value.length > 1) {
				authsList.value.splice(index, 1)
			} else {
				ElMessage.error("最少保留一条")
			}
			stagingA.value = sliceArr(authsList.value, pagesize.value)
			break
		case "2":
			if (authsListItem.value.length > 1) {
				authsListItem.value.splice(index, 1)
			} else {
				ElMessage.error("最少保留一条")
			}
			stagingB.value = sliceArr(authsListItem.value, pagesize.value)
			break
		case "3":
			if (authorityA.value.length > 1) {
				authorityA.value.splice(index, 1)
			} else {
				ElMessage.error("最少保留一条")
			}
			stagingC.value = sliceArr(authorityA.value, pagesize.value)
			break
		case "4":
			if (authorityB.value.length > 1) {
				authorityB.value.splice(index, 1)
			} else {
				ElMessage.error("最少保留一条")
			}
			stagingD.value = sliceArr(authorityB.value, pagesize.value)
			break
	}
}
//用户点击单元格时
const cellClick = row => {
	classificationStr.value = row
}
//删除目录
const delDirectory = val => {
	ElMessageBox.confirm("是否确认删除", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(async () => {
		try {
			await postAxios(`/knowledge/kbSubjectWarehouse/delete?id=${val.id}`)
			ElMessage.success("删除成功")
			created()
			fabu.value = false
		} catch (error) {
			ElMessage.error(error)
			fabu.value = false
		}
	})
}
//清空
function del() {
	ruleForm.name = ""
	ruleForm.sort = 1
	ruleForm.isShow = "2"
	ruleForm.remark = ""
	ruleForm.attribute = ""
	ruleForm.cover = ""
	authsList.value = []
	authsListItem.value = []
	authorityA.value = []
	authorityB.value = []
	searchText.value = ""
	stagingA.value = []
	stagingB.value = []
	stagingC.value = []
	stagingD.value = []
}

//编辑
const edit = async row => {
	title.value = "编辑主题知识库"
	editIf.value = false
	const ress = await getAxios("/kb/kbModel/list?is_deleted=2")
	status.value = row.status
	fabu.value = false
	options.value = ress
	qoptions.value = await getAxios("/system/enums/list?enumName=KbAuth&moduleName=knowledge")
	const res = await getAxios(`/knowledge/kbSubjectWarehouse/findById?id=${row.id}`)
	ruleForm.name = res.name
	ruleForm.sort = res.sort
	ruleForm.isShow = String(res.isShow)
	ruleForm.cover = res.cover
	ruleForm.remark = res.remark
	ruleForm.attribute = res.modelId
	authsList.value = res.knowledgeAuthList
	authsListItem.value = res.classAuthsList
	ids.value = res.id
	if (res.knowledgeAuthList.length && res.classAuthsList.length) {
		listA.value = res.knowledgeAuthList
		listB.value = res.classAuthsList
		stagingA.value = sliceArr(listA.value, pagesize.value)
		stagingB.value = sliceArr(listB.value, pagesize.value)
		currentNameA.value = 1
		currentNameB.value = 1
	}
	visible.value = true
}

//权限调整
const limits = async row => {
	stagingC.value = []
	stagingD.value = []
	quanVisible.value = true
	fabu.value = false
	rowId.value = row.id
	const { classAuthsList, knowledgeAuthList } = await getAxios(`/knowledge/kbWarehouseAuth/findBySwId?swId=${row.id}`)
	if (knowledgeAuthList.length && classAuthsList.length) {
		authorityA.value = knowledgeAuthList
		authorityB.value = classAuthsList
		qoptions.value = await getAxios("/system/enums/list?enumName=KbAuth&moduleName=knowledge")
		listC.value = knowledgeAuthList
		listD.value = classAuthsList
		stagingC.value = sliceArr(listC.value, pagesize.value)
		stagingD.value = sliceArr(listD.value, pagesize.value)
	}
}
const fabu = ref(false)
const isLimits = async () => {
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		const obj = {}
		obj.whId = rowId.value
		obj.knowledgeAuthList = authorityA.value
		obj.classAuthsList = authorityB.value
		let panduan = true
		authorityA.value.forEach(item => {
			if (item.whAuth == null) {
				panduan = false
			}
		})
		if (authorityA.value.length == 1) {
			panduan = true
		}
		if (authorityB.value.length == 1) {
			panduan = true
		} else {
			authorityB.value.forEach(item => {
				if (item.kbAuth == null) {
					panduan = false
				}
			})
		}
		if (panduan) {
			try {
				await postAxios("/knowledge/kbWarehouseAuth/edit", obj)
				ElMessage.success("修改成功")
				currentNameC.value = 1
				currentNameD.value = 1
				quanVisible.value = false
			} catch (error) {
				ElMessage.error(error)
				fabu.value = false
			}
		} else {
			ElMessage.error("请选择权限")
			fabu.value = false
		}
	}
}
const quxiao1 = () => {
	visible.value = false
	del()
}
const quxiao2 = () => {
	quanVisible.value = false
}

//添加成员
const onDialog = val => {
	totalList.value = 0
	currentType.value = +val
	dialogVisible.value = true
	typeStr.value = 1
	key.value = val
	department()

	if (val == 1) {
		tableUser.value = JSON.parse(JSON.stringify(listA.value))
		stagingA.value = sliceArr(authsList.value, pagesize.value)
	} else if (val == 2) {
		tableUser.value = JSON.parse(JSON.stringify(listB.value))
		stagingB.value = sliceArr(authsListItem.value, pagesize.value)
	} else if (val == 3) {
		tableUser.value = JSON.parse(JSON.stringify(listC.value))
		stagingC.value = sliceArr(authorityA.value, pagesize.value)
	} else {
		tableUser.value = JSON.parse(JSON.stringify(listD.value))
		stagingD.value = sliceArr(authorityB.value, pagesize.value)
	}
}
//新增成员点击左侧
const tabListStr = async data => {
	if (typeStr.value == 2) {
		const res = await getAxios(`/knowledge/kbGroups/listById?pId=${data.id}&current=1&size=${pageSizeTable.value}`)
		const ress = await getAxios(`/knowledge/kbGroups/listFind?id=${data.id}&current=1&size=${pageSizeTable.value}`)
		tableDataCheng.value = [].concat(res, ress.records)
		tableDataCheng.value = sliceArr(tableDataCheng.value, pageSizeTable.value)
		totalList.value = +tableDataCheng.value.length
	} else {
		const res = await getAxios(`/system/sysDept/list?parentId=${data.id}&current=1&size=${pageSizeTable.value}`)
		const ress = await getAxios(`/system/sysUser/page?current=1&size=${pageSizeTable.value}&deptId=${data.id}`)
		tableDataCheng.value = [].concat(res, ress.records)
		tableDataCheng.value = sliceArr(tableDataCheng.value, pageSizeTable.value)
		totalList.value = +tableDataCheng.value.length
	}
}
const sliceArr = (arr, pageSize) => {
	const result = []
	let count = 0
	while (count * pageSize < arr.length) {
		result.push(arr.slice(count * pageSize, pageSize * (count + 1)))
		count++
	}
	return result
}
const onSelect = (val, row) => {
	const index = tableUser.value.findIndex(item => item.userId == row.id)
	if (index != "-1") {
		tableUser.value.splice(index, 1)
	} else {
		if (typeStr.value == 1) {
			switch (currentType.value) {
				case 1:
					optimize(row, tableUser.value, "whAuth", 1)
					break
				case 2:
					optimize(row, tableUser.value, "kbAuth", 1)
					break
				case 3:
					optimize(row, tableUser.value, "whAuth", 1)
					break
				case 4:
					optimize(row, tableUser.value, "kbAuth", 1)
					break
			}
		} else {
			switch (currentType.value) {
				case 1:
					optimizes(row, tableUser.value, "whAuth", 1)
					break
				case 2:
					optimizes(row, tableUser.value, "kbAuth", 1)
					break
				case 3:
					optimizes(row, tableUser.value, "whAuth", 1)
					break
				case 4:
					optimizes(row, tableUser.value, "kbAuth", 1)
					break
			}
		}
	}
}
const onSelects = row => {
	const index = tableUser.value.findIndex(item => item.userId == row.id)
	if (index != "-1") {
		tableUser.value.splice(index, 1)
	} else {
		if (typeStr.value == 1) {
			switch (currentType.value) {
				case 1:
					optimize(row, tableUser.value, "whAuth", 1)
					break
				case 2:
					optimize(row, tableUser.value, "kbAuth", 1)
					break
				case 3:
					optimize(row, tableUser.value, "whAuth", 1)
					break
				case 4:
					optimize(row, tableUser.value, "kbAuth", 1)
					break
			}
		} else {
			switch (currentType.value) {
				case 1:
					optimizes(row, tableUser.value, "whAuth", 1)
					break
				case 2:
					optimizes(row, tableUser.value, "kbAuth", 1)
					break
				case 3:
					optimizes(row, tableUser.value, "whAuth", 1)
					break
				case 4:
					optimizes(row, tableUser.value, "kbAuth", 1)
					break
			}
		}
	}
}
function optimize(row, item, auth, nu) {
	if (row.name) {
		item.push({
			userName: row.name,
			userId: row.id,
			[auth]: nu,
			status: 3,
		})
	} else {
		item.push({
			userName: row.realName,
			userId: row.id,
			[auth]: nu,
			status: 1,
		})
	}
}
function optimizes(row, item, auth, nu) {
	if (row.name) {
		item.push({
			userName: row.name,
			userId: row.id,
			[auth]: nu,
			status: 2,
		})
	} else {
		item.push({
			userName: row.realName,
			userId: row.id,
			[auth]: nu,
			status: 1,
		})
	}
}
const tabclick = event => {
	if (event.props.label == "按部门分类") {
		typeStr.value = 1
	} else {
		typeStr.value = 2
	}
	department()
	tableDataCheng.value = []
	totalList.value = 0
}
async function department() {
	if (typeStr.value == 1) {
		dataSourceList.value = await getAxios("/system/sysDept/list")
	} else {
		dataSourceList.value = await getAxios("/knowledge/kbGroups/list")
	}
}

const onAddList = () => {
	dialogVisible.value = false
	tableDataCheng.value = []
	activeName.value = "department"
	typeStr.value = 1
	switch (currentType.value) {
		case 1:
			authsList.value = tableUser.value
			listA.value = tableUser.value
			break
		case 2:
			authsListItem.value = tableUser.value
			listB.value = tableUser.value
			break
		case 3:
			authorityA.value = tableUser.value
			listC.value = tableUser.value
			break
		case 4:
			authorityB.value = tableUser.value
			listD.value = tableUser.value
			break

		default:
			break
	}

	stagingA.value = sliceArr(authsList.value, pagesize.value)
	stagingB.value = sliceArr(authsListItem.value, pagesize.value)
	stagingC.value = sliceArr(authorityA.value, pagesize.value)
	stagingD.value = sliceArr(authorityB.value, pagesize.value)
}

watch(tableDataCheng, () => {
	nextTick(() => {
		if (tableDataCheng.value.length) {
			tableDataCheng.value[currentTable.value - 1].forEach(item => {
				if (tableUser.value.some(v => v.userId == item.id)) {
					multipleTableRef.value.toggleRowSelection(item, true)
				} else {
					multipleTableRef.value.toggleRowSelection(item, false)
				}
			})
		}
	})
})
watch(currentTable, () => {
	nextTick(() => {
		if (tableDataCheng.value.length) {
			tableDataCheng.value[currentTable.value - 1].forEach(item => {
				if (tableUser.value.some(v => v.userId == item.id)) {
					multipleTableRef.value.toggleRowSelection(item, true)
				} else {
					multipleTableRef.value.toggleRowSelection(item, false)
				}
			})
		}
	})
})
watch(
	tableUser,
	(newValue, oldValue) => {
		nextTick(() => {
			if (tableDataCheng.value.length) {
				tableDataCheng.value[currentTable.value - 1].forEach(item => {
					if (tableUser.value.some(v => v.userId == item.id)) {
						multipleTableRef.value.toggleRowSelection(item, true)
					} else {
						multipleTableRef.value.toggleRowSelection(item, false)
					}
				})
			}
		})
	},
	{ deep: true }
)

const selectAllTable = row => {
	if (row.length == 0) {
		tableDataCheng.value[currentTable.value - 1].forEach(it => {
			const index = tableUser.value.findIndex(item => item.userId == it.id)
			if (index != "-1") {
				tableUser.value.splice(index, 1)
			}
		})
	} else {
		row.forEach(i => {
			const index = tableUser.value.findIndex(item => item.userId == i.id)
			if (index == "-1") {
				if (typeStr.value == 1) {
					switch (currentType.value) {
						case 1:
							optimize(i, tableUser.value, "whAuth", 1)
							break
						case 2:
							optimize(i, tableUser.value, "kbAuth", 1)
							break
						case 3:
							optimize(i, tableUser.value, "whAuth", 1)
							break
						case 4:
							optimize(i, tableUser.value, "kbAuth", 1)
							break
					}
				} else {
					switch (currentType.value) {
						case 1:
							optimizes(i, tableUser.value, "whAuth", 1)
							break
						case 2:
							optimizes(i, tableUser.value, "kbAuth", 1)
							break
						case 3:
							optimizes(i, tableUser.value, "whAuth", 1)
							break
						case 4:
							optimizes(i, tableUser.value, "kbAuth", 1)
							break
					}
				}
			}
		})
	}
}
const cancellationB = () => {
	dialogVisible.value = false
	tableDataCheng.value = []
	activeName.value = "department"
	typeStr.value = 1
	searchText.value = ""
}

const onSearch = async () => {
	const { user, dept } = await getAxios(
		`/system/sysUser/findToDept?type=3&name=${searchText.value}&size=${findSize.value}&current=${findpage.value}`
	)
	tableDataCheng.value = [...user, ...dept]
	tableDataCheng.value = sliceArr(tableDataCheng.value, pageSizeTable.value)
	totalList.value = +user.length + +dept.length
	searchText.value = ""
}
const delTableList = () => {
	tableUser.value.splice(1)
}
const clickDelTag = index => {
	if (tableUser.value.length == 1) {
		return ElMessage.error("最少保留一个")
	}
	if (index != 0) {
		tableUser.value.splice(index, 1)
	} else {
		ElMessage.error("不能删除创建者")
	}
}

const upload = ref("")
const cropper = ref("")

// 图片裁剪
function onChangeUpload(file) {
	cropper.value.handleChangeUpload(file)
	upload.value.clearFiles()
	imgRef.value.clearValidate()
}
//上传成功
const handleAvatarSuccess = res => {
	ruleForm.cover = res.url
}
//刷新模板
const refresh = async () => {
	try {
		const res = await getAxios("/kb/kbModel/list?is_deleted=2")
		options.value = res
	} catch (error) {
		ElMessage.error(error)
	}
}
// const onSuccess = () => {
// 	console.log(1)
// }
</script>
<style lang="scss" scoped>
@import "/style/basis";

.option-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
	gap: 20px;
}
.zhiShiFenLei {
	background-color: #f8f8f8;
	// height: 100%;

	.quan-dialog {
		.quanXian-right {
			display: flex;
			justify-content: flex-end;
			// padding: 30px 100px 30px 0;
			// border-bottom: 1px solid #ebeef5;
		}
		.quanXian-select {
			width: 140px;

			:deep(.el-input__wrapper) {
				box-shadow: none;
				border: 0;
				padding: 0;
			}
		}

		.mt50 {
			margin-top: 25px;
		}

		.quanXian-content {
			padding: 19px 25px;
			border: 1px solid #ebeef5;
			border-top: 0;
		}

		.shan-icon {
			width: 20px;
			margin-left: 90px;
		}

		.tou-icon {
			width: 15px;
			margin-right: 10px;
		}

		.title {
			background: #f0f2f5;
			border: 1px solid #ebeef5;
			padding: 15px 25px;

			.quanXian-icon {
				width: 15px;
			}
		}
	}

	.cheng-dialog {
		padding: 25px 24px;
		.flex {
			display: flex;
			.refresh {
				// display: flex;
				margin-left: 20px;
				// cursor: pointer;
				// .refresh-icon {
				// 	padding-top: 3px;
				// }
			}
		}
		.quanXian-select {
			width: 90px;

			:deep(.el-input__wrapper) {
				box-shadow: none;
				border: 0;
				padding: 0;
			}
		}
		.label-icon {
			margin-left: 5px;
			padding-top: 13px;
		}
		.quanXian-content {
			border-bottom: 1px solid #ebeef5;
			margin-left: 200px;
			margin-right: 20px;
			@include maxWidth(768) {
				padding-left: 0;
			}

			&:last-of-type {
				.quanXian-right {
					border-bottom: 0;
				}
			}
		}

		.shan-icon {
			width: 20px;
			margin-left: 145px;
		}
		.quanXian-right {
			display: flex;
			justify-content: flex-end;
			padding: 20px 100px 20px 0;

			@include maxWidth(768) {
				padding: 30px 0;
			}
		}
		.tou-icon {
			width: 15px;
			margin-right: 10px;
		}

		.form-footer {
			padding-top: 20px;
			display: flex;
			justify-content: center;

			:deep(.el-button) {
				margin-right: 25px;
			}
		}

		.paixu-label {
			padding-left: 32px;
			padding-right: 12px;
		}

		.title {
			padding-bottom: 15px;

			.quanXian-icon {
				width: 15px;
				margin-right: 8px;
			}
		}

		.add-btn {
			border: 1px solid #dcdfe6;
			border-left: 0;
			border-radius: 0 3px 3px 0;
			margin-bottom: -2px;
			width: 40px;

			font-size: 15px;
			background: #f5f7fa;
			color: #91949a;
		}

		:deep(.add-btn .el-button__text--expand) {
			letter-spacing: 0;
			margin-right: 0;
		}

		:deep(.el-form-item__label) {
			width: 200px;
			font-size: 15px;
			color: #606266;
			padding: 0 12px 0 0;
			white-space: nowrap;
			@include maxWidth(768) {
				width: 100px;
			}
		}
		:deep(.el-input__icon) {
			display: none;
		}
	}

	:deep(.el-checkbox-group) {
		padding-left: 22px;
	}

	:deep(.el-radio__input.is-checked .el-radio__inner::after) {
		background: #fff;
	}

	// :deep(.cheng-dialog .bu-select) {
	// 	width: 100% !important;
	// }

	:deep(.bu-select .el-input__wrapper) {
		border-radius: 3px 0 0 3px !important;
	}

	:deep(.cheng-dialog .el-select__tags .el-tag--info) {
		background: #f4faff;
		border: 1px solid #2972fa;
		border-radius: 13px;
		color: #2972fa;
	}

	.left-bottom {
		padding: 15px;

		.table-head {
			margin-bottom: 15px;

			:deep(.el-input) {
				width: 215px;
				height: 25px;
				border-radius: 3px;
				margin-right: 5px;
			}

			.primary {
				width: 90px;
				height: 30px;
				border-radius: 3px;
			}

			.danger {
				width: 90px;
				height: 30px;
				border-radius: 3px;
				margin-left: 10px;
			}
		}

		:deep(.el-table) {
			border: 1px solid #eceef5;
		}

		:deep(.el-table th.el-table__cell) {
			background-color: #f4f7fa;
		}

		:deep(.el-table .el-table__cell) {
			height: 50px;
			color: #303133;
		}
	}

	.left {
		margin: 25px;
		height: 100%;
		overflow-y: scroll;
	}
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
	.avatar-uploader .el-upload {
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		// transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 150px;
		height: 150px;
		text-align: center;
		border: 1px dashed #e4e4e4;
	}
	.selectDel {
		cursor: pointer;
		margin-left: 15px;
		width: 75px;
		font-size: 14px;
	}
}

.dialog-content-cheng {
	:deep(.choice .el-tag) {
		height: 30px;
		background: #f4faff;
		margin-left: 15px;
		padding: 0 12px;
		margin-bottom: 7px;
	}

	.choice {
		margin-top: 10px;
		padding: 18px 25px 19px 30px;
		border-top: 1px solid rgba(41, 114, 250, 0.2);
		border-bottom: 1px solid rgba(41, 114, 250, 0.2);
	}

	:deep(.clear-btn) {
		width: 70px;
		height: 25px;
		border-radius: 3px;
	}

	:deep(.el-table th.el-table__cell) {
		background: #f4faff;
	}

	:deep(.el-table) {
		margin-top: 25px;
		color: #787a7e;
	}

	:deep(.search-input .el-input__wrapper) {
		height: 40px;
		background-color: #f5f6f7;
	}

	.search-btn {
		background-color: #2972fa;
		color: #fff;
		height: 40px;
		border-top-left-radius: 0;
		border-bottom-left-radius: 0;
	}

	.dleft {
		width: 40%;
		height: 520px;
		margin: 0;
		margin-right: 23px;
	}

	:deep(.el-tree-node__content:hover) {
		background: #f4faff;
	}

	:deep(.el-tree-node__expand-icon) {
		color: #006eff;
	}

	:deep(.el-tree-node__expand-icon.is-leaf) {
		color: #fff;
	}

	.gongsi-icon {
		width: 15px;
		margin-right: 4px;
	}

	.tree-box {
		height: 350px;
		margin-top: 10px;
		padding: 25px 5px;
		overflow-y: auto;
	}

	.tab-content {
		background: #f4faff;
		border: 1px solid #e6ebf5;
		border-radius: 5px;
		padding: 30px 20px;
	}
}
:deep(.el-select-dropdown__item) {
	height: auto !important;
}
.suoyou {
	color: #999;
}

:deep(.quan-dialog) {
	width: 800px !important;
}
:deep(.el-select--small) {
	@include maxWidth(500) {
		width: 100px;
	}
}
.elTag {
	margin-top: 10px;
	margin-left: 42%;
}
.pag-centent {
	display: flex;
	justify-content: center;
}
// :deep(.el-button) {
// 	&:focus {
// 		color: #606266;
// 		background-color: #fff;
// 	}
// }
</style>
